package com.lghs.stutor;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class ReviewSession extends Activity {
    Vital vital = new Vital();
    Intent i;
    ListView lv_messages;
    RatingBar rb_rate;
    Button btn_submit;
    ArrayList<String> listItems;
    ArrayAdapter<String> adapter;
    ProgressDialog pDialog;
    //
    HttpGet httpGet;
    HttpResponse execute;
    DefaultHttpClient client;
    InputStream content;
    BufferedReader buffer;
    static int rating;
    static String tutorname, username, url, type, sessionid;

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        i = new Intent();
        if (!type.equals("student"))
            i.setClass(getApplicationContext(), Accountinfo.class);
        else
            i.setClass(getApplicationContext(), Home.class);
        i.putExtra("uname", username);
        i.putExtra("firstlaunch","no");
        startActivity(i);
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_review_session);
        listItems = new ArrayList<String>();
        i = getIntent();
        initialization();
        listeners();
        lv_messages.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    public void initialization() {
        lv_messages = (ListView) findViewById(R.id.listView1);
        rb_rate = (RatingBar) findViewById(R.id.ratingBar1);
        btn_submit = (Button) findViewById(R.id.button1);
        rating = 5;
        tutorname = "";
        username = "";
        sessionid = "";
        type = "";
        if (i.getStringExtra("type") != null)
            type = i.getStringExtra("type");
        username = i.getStringExtra("uname");
        if (i.getStringExtra("tutorname") != null)
            tutorname = i.getStringExtra("tutorname");
        sessionid = i.getStringExtra("sessionid");
        if (i.getStringArrayListExtra("listli") != null)
            listItems = i.getStringArrayListExtra("listli");
        else
            listItems = new ArrayList<String>();
        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, listItems);
        if (!type.equals("student")) {
            rb_rate.setEnabled(false);
            btn_submit.setEnabled(false);
            new getmessages().execute();
        }
        new checkrating().execute();

    }

    public void listeners() {
        rb_rate.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
            public void onRatingChanged(RatingBar arg0, float arg1, boolean arg2) {
                rating = (int) arg1;
            }

        });
        btn_submit.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                new ratetutor().execute();
            }
        });
    }

    class ratetutor extends AsyncTask<String, Void, String> {

        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ReviewSession.this, R.style.Theme_MyDialog);
            pDialog.setMessage("ReviewSession this Session");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.setTitle("ReviewSession Session");
            pDialog.setIcon(com.lghs.stutor.R.drawable.idk);
            pDialog.show();
        }

        protected String doInBackground(String... urls) {
            String response = "";
            url = "http://" + vital.host + "/rating.php?u=" + tutorname + "&r=" + rating + "&s=" + sessionid;

            try {
                client = new DefaultHttpClient();
                httpGet = new HttpGet(url);
                execute = client.execute(httpGet);
                content = execute.getEntity().getContent();

                buffer = new BufferedReader(new InputStreamReader(content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    response = s;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }

        protected void onPostExecute(String result) {
            pDialog.dismiss();
            i = new Intent();
            i.setClass(getApplicationContext(), Home.class);
            i.putExtra("uname", username);
            i.putExtra("firstlaunch","no");
            startActivity(i);
            finish();
        }
    }

    class getmessages extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        protected String doInBackground(String... urls) {
            String response = "";
            url = "http://" + vital.host + "/getmessages.php?s=" + sessionid
                    + "&mr=0&t=" + type;
            try {
                client = new DefaultHttpClient();
                httpGet = new HttpGet(url);
                execute = client.execute(httpGet);
                content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(
                        new InputStreamReader(content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    if (s.contains("-")) {
                        s = s.replace("{/001}", "+");
                        s = s.trim();
                        s = s.replaceFirst(String.valueOf(s.substring(0,
                                s.indexOf("-"))), "");
                        s = s.replaceFirst("-", "");
                        // s = s.replace(String.valueOf(lastmessageid), "");
                        listItems.add(s);
                        response = s;
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }

        @Override
        protected void onPostExecute(String result) {
            if (!result.trim().equals(""))
                adapter.notifyDataSetChanged();
        }
    }

    class checkrating extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        protected String doInBackground(String... urls) {
            String response = "";
            url = "http://" + vital.host + "/checkrating.php?s=" + sessionid;
            try {
                client = new DefaultHttpClient();
                httpGet = new HttpGet(url);
                execute = client.execute(httpGet);
                content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(
                        new InputStreamReader(content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    response = s.trim();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }

        @Override
        protected void onPostExecute(String result) {
            if (result.equals("0")){
                rb_rate.setEnabled(true);
                btn_submit.setEnabled(true);
            }
            else
            {
                rb_rate.setRating(Float.parseFloat(result));
                rb_rate.setEnabled(false);
                btn_submit.setEnabled(false);
            }

        }
    }
}